<template>
  <div style="margin-left: 2%;margin-right: 2%;margin-top: 10px">

    <!-- 主要内容 -->
    <el-main>
      <el-header>
        <el-col :span="6">
          <span>项目编号：{{ formData.projectCode }}</span>
        </el-col>
        <el-col :span="6">
          <span>项目名称：{{ formData.projectName  }}</span>
        </el-col>
        <el-col :span="6">
          <span v-if="formData.purchaseCategoryId === '1' ">采购类别：货物类</span>
          <span v-else-if="formData.purchaseCategoryId === '2'">采购类别：服务类</span>
          <span v-else-if="formData.purchaseCategoryId === '3'">采购类别：工程类</span>
          <span v-else>采购类别：其他采购类别</span>
        </el-col>
        <el-col :span="6">
          <span>预算金额：{{ formData.budget }}元</span>
        </el-col>
      </el-header>

      <!-- 表格内容 -->
      <el-table :data="approvalData" style="width: 100%" border>
        <el-table-column prop="profileName" label="验收资料名称"></el-table-column>
        <el-table-column prop="uploadTime" label="上传时间"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button @click="downloadFile(scope.$index, scope.row)">下载</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 审批状态 -->
      <div class="showCurrentStatus" v-if="formData">
        <strong>当前审批状态:</strong>  {{ formData.accApproveStatus }}
      </div>


      <!-- 审批意见 -->
      <el-form>
        <el-form-item  class="inputApproval" label="审批意见:">
          <el-input v-model="accApproveSuggestion" type="textarea" rows="4" placeholder="请输入审批意见"></el-input>
        </el-form-item>
      </el-form>
      <div style="margin-left: 220px;margin-top: 30px;">
            <span>
            <el-button type="primary" @click="approve" :disabled="formData.accApproveStatus === '审批通过' || formData.accSubstatus === '未提交'">审批通过</el-button>
            </span>
        <span style="margin-left: 40px;">
            <el-button type="primary" v-if="canCancel" @click="cancel" :disabled="formData.archiveSubmitStatus === '已提交'">审批退回</el-button>
            </span>
        <span style="margin-left: 40px;">
              <!-- 返回按钮 -->
              <el-button  @click="goBack" type="primary">返回</el-button>
            </span>
      </div>
    </el-main>
  </div>
</template>

<script>
import JSZip from 'jszip';
import FileSaver from 'file-saver';
import { accApproved } from "@/api/acceptanceApproval/acceptanceApproval.js";
import { accCancel } from "@/api/acceptanceApproval/acceptanceApproval.js";
import { selectAllApprovalData }from "@/api/acceptanceApproval/acceptanceApproval.js";
import request from "@/utils/request";

export default {
  data() {
    return {
      //保存传递过来的数据
      formData: {
        projectCode: '',
        projectName: '',
        categoryName: '',
        budget: '',
        projectId:'',
        accApproveStatus:'',
        accSubstatus:'',
        archiveApproveStatus:'',
        archiveSubmitStatus:'',
        accApproveSuggestion:'',
      },
      rules: {
        contact: [{required: true, message: '请输入', trigger: ['blur', 'change']}],
        telephone: [{required: true, message: '请输入', trigger: ['blur', 'change']}],
        supplierName: [{required: true, message: '请输入', trigger: ['blur', 'change']}],
      },
      //table表格里的新数据,此处添加的值仅为测试值，上线代码前请将其删除
      approvalData: [
        // {
        //   id:'1',
        //   profileName: '到货验收资料',
        //   filePath:'',
        //   uploadTime: '2023-07-26 12:34:56',
        // },
        // 可以添加更多的初始数据项
      ],

      // 用于存储审批注释的新数据属性
      accApproveSuggestion: '',

    };
  },

  created() {
    // 接收路由传递的数据
    this.formData.projectCode = this.$route.params.projectCode;
    this.formData.projectName = this.$route.params.projectName;
    this.formData.purchaseCategoryId = this.$route.params.purchaseCategoryId;
    this.formData.budget = this.$route.params.budget;
    this.formData.accApproveStatus = this.$route.params.accApproveStatus;
    this.formData.accSubstatus = this.$route.params.accSubstatus;
    this.formData.archiveApproveStatus = this.$route.params.archiveApproveStatus;
    this.formData.archiveSubmitStatus = this.$route.params.archiveSubmitStatus;
    this.formData.accApproveSuggestion = this.$route.params.accApproveSuggestion;
    this.formData.projectId = this.$route.params.projectId;

    this.accApproveSuggestion= this.$route.params.accApproveSuggestion;
    this.selectAllApprovalDataList()
  },

  methods: {

    //初始化approvalData里的数据
    async selectAllApprovalDataList() {
      let data ={ projectId: this.formData.projectId }
      try {
        const response = await selectAllApprovalData(data);
        if (response.data.code === 200) {
          this.approvalData = response.data.data;
          console.log(this.formData.archiveSubmitStatus)
        } else {
          this.$message.error(response.data.msg);
        }
      } catch (error) {
        console.error('Error fetching approval data:', error);
      }
    },


    //下载
    async downloadFile(index, row){
      let data={
        'profileName':row.profileName,
        'filePath':row.filePath,
      }
      console.log(data)
      let res=await request(
          {
            url: "/acceptanceApproval/downloadfile",
            method: "post",
            responseType: 'blob',
            data:data
          }
      )
      console.log(res.data)
      let blob = new Blob([res.data], {type: 'application/octet-stream'})
      // 创建一个临时的URL，用于下载文件
      let url = window.URL.createObjectURL(blob)
      // 创建一个a标签，指定下载链接和文件名
      let link = document.createElement('a')
      link.href = url
      link.download = row.filePath // 这里可以根据实际情况指定文件名和扩展名
      // 触发a标签的点击事件，开始下载文件
      link.click()
      // 释放URL资源
      window.URL.revokeObjectURL(url)
    },

    //审批通过
    async approve() {
      if(this.formData.accSubstatus === '已提交') {
        // 发出事件以更新index中的审批状态
        this.$confirm('确认通过审批吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let data = {projectId: this.formData.projectId, accApproveSuggestion: this.accApproveSuggestion}
          let res = await accApproved(data)
          if (res.data.code === 200) {
            this.$message({
              type: 'success',
              message: '通过成功!'
            });
            this.formData.accApproveStatus = '审批通过';
            // 审批后重置审批意见输入字段
            this.accApproveSuggestion = '';

          } else {
            this.$message.error(res.data.msg)
          }

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          });
        });
      }else {
        this.$message.error("请确认验收审批提交状态");
      }
    },

    canCancel() {
      // 检查审批状态是否已为“审批通过“或者如果”审批通过”按钮
      return this.formData && this.formData.accApproveStatus === '审批通过';
    },


    //审批退回
    async cancel() {
      if(this.formData.archiveSubmitStatus !== '已提交') {
        // 发出事件以更新index中的审批状态
        this.$confirm('确认退回审批吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let data = {projectId: this.formData.projectId, accApproveSuggestion: this.accApproveSuggestion}
          let res = await accCancel(data)
          if (res.data.code === 200) {
            this.$message({
              type: 'success',
              message: '退回成功!'
            });
            this.formData.accApproveStatus = '退回';
            // 审批后重置审批意见输入字段
            this.accApproveSuggestion = '';
            this.formData.accSubstatus = '未提交';
          } else {
            this.$message.error(res.data.msg)
          }

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          });
        });
      }else{
        this.$message.error("不可退回，请确认归档审批提交状态")
      }
    },

    //当点击返回按钮，返回到potentialSuppliers页面
    goBack() {
      this.$router.push('acceptanceApproval');
    },
  },

};
</script>

<style>
.showCurrentStatus{
  margin-top: 30px;
}

.inputApproval{
  margin-top: 30px;
}

</style>

